package server;

import java.io.IOException;

import netPacks.message;

public class matcher extends Thread{

	private matcher(){}
	
	private static volatile matcher instance = null;
	
    public static matcher getInstance() {
        if (instance == null){
            synchronized (matcher.class){
                    if (instance == null){
                        instance = new matcher();
                    }
            }
        }
        return instance;
    }
    
    public synchronized void run(){
        while(true){
            if(mainServer.getInstance().readyQ.size()>1){
	             clientConnection p1 = (clientConnection) mainServer.getInstance().readyQ.pop();
	             clientConnection p2 = (clientConnection) mainServer.getInstance().readyQ.pop();
	             //message get1 = new message();
	             //get1.setAction("getReady");
	             //get1.setUserId(p1.id);
	             //message get2 = new message();
	             //get2.setAction("getReady");
	             //get2.setUserId(p2.id);
	             //try{
	            //	System.out.println("getting ready...");
	             //   p2.oos.writeObject(get2);
	            //	p2.oos.writeObject(get1);
	             //}
	             //catch(IOException e){
	            //	 System.err.println("Cannot send oponent IP addresses. Matching failed:\n"+e.getMessage());
	             //}
	             //System.out.println("ready procedure complete");
	             message hostMsg = new message();
	             hostMsg.setAction("youAreHost");
	             hostMsg.setUserId(p2.id);
	             message p1Msg = new message();
	             p1Msg.setAction("match");
	             p1Msg.setUserId(p1.id);
	             message p2Msg = new message();
	             p2Msg.setAction("match");
	             p2Msg.setUserId(p2.id);
	             try{
	            	System.out.println("matching...");
	                p2.oos.writeObject(hostMsg);
	            	p2.oos.writeObject(p1Msg);
	                p1.oos.writeObject(p2Msg);
	                System.out.println("player match succeeded");
	             }
	             catch(IOException e){
	                 System.err.println("Cannot send oponent IP addresses. Matching failed:\n"+e.getMessage());
	             }
	         }
        }
    }
}
